<?php
namespace app\index\controller;

use app\index\controller\User;
use app\index\model\Ban;
use app\index\model\DCharacter;
use think\Controller;

/**
 * Crontab scan()方法由系统计划任务程序定期调用，实现用户封禁账号逾期解禁
 */
class Crontab extends Controller
{

    private $character;
    private $user;
    public function _initialize()
    {
        $this->character = new DCharacter();
        $this->user      = new User();
    }

    /**
     * 封禁表扫描解锁
     *
     * @DateTime 2017-11-29
     * @return   [type]
     */
    public function scan()
    {
        try {

            //获取查询结果
            //
            $rtn = $this->getOverdueAccount();

            //逾期禁言解锁
            if (!empty($rtn['comment'])) {

                foreach ($rtn['comment'] as $v) {

                    //执行禁言角色ID解禁
                    $this->character->changeDontalkTo($v['uid'], 0);

                    //增加修改标记
                    Ban::where('id', $v['id'])
                        ->update(['unsealed' => 1]);
                }
            }

            //逾期账号解锁
            if (!empty($rtn['account'])) {

                foreach ($rtn['account'] as $v) {

                    //执行封禁账号解封
                    $this->user->banAccount($v['uid'], 1);

                    //增加修改标记
                    Ban::where('id', $v['id'])
                        ->update(['unsealed' => 1]);
                }
            }

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
    /**
     * 获取封禁表逾期账号
     *
     * @DateTime 2017-11-29
     * @return   array 操作账号数组
     */
    public function getOverdueAccount()
    {
        try {

            $rtn            = [];
            $rtn['account'] = [];
            $rtn['comment'] = [];

            //获取所有当前时间晚于封禁截止时间的未解封记录

            $temp = Ban::where("UNIX_TIMESTAMP(`deadline`)<=UNIX_TIMESTAMP(NOW()) AND 0=`unsealed`")
                ->field("`id`,`uid`,`operation`")
                ->select();

            if ($temp) {

                foreach ($temp as $data) {
                    $id        = $data->getData('id');
                    $uid       = $data->getData('uid');
                    $operation = $data->getData('operation');

                    if (0 == $operation) {
                        array_push($rtn['comment'], ['id' => $id, 'uid' => $uid]);

                    } else if (1 == $operation) {
                        array_push($rtn['account'], ['id' => $id, 'uid' => $uid]);
                    }
                }
            }

            return $rtn;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
